'use strict';
let fs = require('fs');
let path = require('path');
let router = require('koa-router')();

function filesFind() {
    let file = fs.readdirSync(__dirname);
    let filter = file.filter(item => {
        return item.endsWith('.js') && item !== 'index.js';
    })
    return filter;
}
 
function login(files) {
    files.forEach(element => {
        let fullPath = path.join(__dirname, element);
        let routerFile = require(fullPath);
        for (let i in routerFile) {
            let type = routerFile[i][0];
            let fn = routerFile[i][1];
            if (type === 'post') {
                router.post(i, fn);
            } else if (type === 'put') {
                router.put(i, fn);
            } else if (type === 'delete') {
                router.delete(i, fn);
            } else if (type === 'get') {
                router.get(i,fn);
            }
        }
    });
}

module.exports = function () {
    let controllers = filesFind();
    login(controllers);
    return router.routes();
}